package com.bit.meta;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * bit-supper-Zkutil
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/10/12 上午 11:56
 */
@Component
public class ZkUtil {

    @Autowired
    private CuratorFramework zk;


    /**
     * 创建节点
     *
     * @param path
     * @param mode
     * @param data
     * @throws Exception
     */
    public String createPath(String path, CreateMode mode, String data) throws Exception {
        Stat stat = zk.checkExists().forPath(path);
        if (stat == null) {
            //不存在时创建
            path = zk.create().withMode(mode).forPath(path, StringUtils.isEmpty(data) ? "".getBytes() : data.getBytes());
        }
        return path;
    }

    /**
     * 获取孩子节点
     *
     * @param path
     * @return
     * @throws Exception
     */
    public List<String> child(String path) throws Exception {
        return zk.getChildren().forPath(path);
    }


    /**
     * 监听
     *
     * @param path
     */
    public void watch(String path, Watcher watcher) throws Exception {
        zk.getData().usingWatcher(watcher).forPath(path);
    }
}
